package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.LoginPermissions;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个拦截器,用于登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //跨域预查询放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //强转为HandlerMethod类型用来获取它的注解方法等等
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        //获取url上的token
        String token = request.getHeader("token");
        //判断Redis中该用户是否有登录
        UserInfo user = userInfoRedisService.getUserByToken(token);

        /*//判断:如果没有用户就不放行,有就放行
        if (user == null){
            //中文可能会乱码
            response.setContentType("application/json;charset:utf-8");
            response.getWriter().print(JSON.toJSONString(JsonResult.noLogin()));
        }*/

        //判断当前访问的资源是否有贴需要登录的注解
        if (handlerMethod.hasMethodAnnotation(LoginPermissions.class)) {
            //判断:如果没有用户就不放行,有就放行
            if (user == null) {
                response.setContentType("application/json;charset:utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }

}
